package cn.sylinx.common.ext.web;

import java.io.Writer;
import java.util.Map;

import javax.servlet.ServletResponse;

import com.alibaba.fastjson.JSON;

import cn.sylinx.common.ext.exception.WrappedException;
import cn.sylinx.common.ext.map.ParameterMap;
import cn.sylinx.common.lang.StringUtil;

public abstract class BaseController {

	public static final String PRODUCES = "application/json; charset=UTF-8";

	/**
	 * html 换行
	 */
	protected static final String HTML_LINE_FEED = "<br>";

	/**
	 * 500错误
	 */
	protected static final String ERROR_500 = Result.toJson(Result.error500());

	/**
	 * 404错误
	 */
	protected static final String ERROR_404 = Result.toJson(Result.error404());

	protected String toJson(Object obj) {
		return JSON.toJSONString(obj);
	}

	protected <T> T toObject(String jsonStr, Class<T> clazz) {
		return JSON.parseObject(jsonStr, clazz);
	}

	@SuppressWarnings("rawtypes")
	protected <T> T mapToObject(Map map, Class<T> clazz) {
		return toObject(toJson(map), clazz);
	}

	protected String toJsonResult(Result r) {
		return Result.toJson(r);
	}

	protected String toJsonResult(String code, Object data) {
		return Result.toJson(Result.apply(code, data));
	}

	protected void write(ServletResponse response, String content) {

		Writer wr = null;
		try {
			response.setCharacterEncoding("UTF-8");
			wr = response.getWriter();
			wr.write(content);
			wr.flush();
		} catch (Exception e) {
			try {
				wr.write(Result.error500ForJson("系统异常，请稍候重试"));
				wr.flush();
			} catch (Exception e1) {
			}
		} finally {
			try {
				wr.close();
			} catch (Exception e1) {
			}
		}
	}

	/**
	 * 
	 * @param models
	 * @param name
	 * @return
	 */
	protected String assertParameterNotNullAndGet(ParameterMap models, String name) {
		String value = models.getString(name);
		if (StringUtil.isBlank(value)) {
			throw new WrappedException("参数" + name + "为空");
		}
		return value;
	}

	/**
	 * 检测字段
	 * 
	 * @param models
	 * @param fields
	 * @return
	 */
	protected boolean hasBlank(ParameterMap models, String... fields) {

		if (models == null || fields == null || fields.length == 0) {
			return false;
		}

		for (String field : fields) {

			Object v = models.get(field);
			if (v == null) {
				return true;
			}

			if (v instanceof String) {

				if (StringUtil.isBlank((String) v)) {
					return true;
				}
			}
		}

		return false;
	}

	/**
	 * 是否存在空字符存
	 * 
	 * @param strs
	 * @return
	 */
	protected boolean hasBlank(String... strs) {

		if (strs == null || strs.length == 0) {
			return false;
		}

		for (String str : strs) {
			if (StringUtil.isBlank(str)) {
				return true;
			}
		}

		return false;
	}

	protected boolean hasBlank(Object... models) {

		if (models == null || models.length == 0) {
			return false;
		}

		for (Object m : models) {
			if (m == null || StringUtil.isBlank(m.toString())) {
				return true;
			}
		}
		return false;
	}
}
